import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from '@/utils/request'
import type { ApiResponse } from '@/types/api'
import { formatDate, formatDateTime, formatCurrency } from '@/utils/format'

// 路由
const router = useRouter()
const route = useRoute()

// 加载状态
const loading = ref(false)

// 商机详情
const chanceDetail = ref({
  id: '',
  name: '',
  customer_name: '',
  amount: 0,
  probability: 0,
  status_title: '',
  expected_time: '',
  creator_name: '',
  belong_name: '',
  create_time: '',
  update_time: '',
  remark: '',
})

// 跟进记录
const traces = ref<any[]>([])

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取商机详情
const getChanceDetail = async (id: string) => {
  try {
    loading.value = true

    // 调用新后端接口获取商机详情
    const response: ApiResponse<any> = await axios.get(`/api/customer/chance/detail/${id}`)

    // 统一从ApiResponse中获取并解析数据
    if (response.code === 0) {
      chanceDetail.value = response.data
      // 获取跟进记录
      getTraces(id)
    } else {
      ElMessage.error(response.msg || '获取商机详情失败')
    }
  } catch (error) {
    ElMessage.error('获取商机详情失败')
  } finally {
    loading.value = false
  }
}

// 获取跟进记录
const getTraces = async (chanceId: string) => {
  try {
    // 调用新后端接口获取跟进记录
    const response: ApiResponse<any[]> = await axios.get(`/api/customer/chance/trace/view`, {
      params: { chance_id: chanceId },
    })

    // 统一从ApiResponse中获取并解析数据
    if (response.code === 0) {
      traces.value = response.data
    } else {
      ElMessage.error(response.msg || '获取跟进记录失败')
    }
  } catch (error) {
    ElMessage.error('获取跟进记录失败')
  }
}

// 初始化数据
const init = () => {
  const chanceId = route.params.id as string
  if (chanceId) {
    getChanceDetail(chanceId)
  }
}

// 组件挂载时初始化
onMounted(() => {
  init()
})

// 导出所有需要在模板中使用的变量和方法
export {
  // 响应式数据
  loading,
  chanceDetail,
  traces,

  // 方法
  goBack,
  formatDate,
  formatDateTime,
  formatCurrency,
}
